<!--表单数据-->
<template>
  <div class='home' style="min-height: 200px;">
    <!--表单信息-->
    <el-row>
      <el-col :span="12"><div class="grid-content bg-purple-light" style="margin-top: 10px;">
        <h4 class="wf_h">表单信息</h4>
      </div>
      </el-col>
    </el-row>
    <!--v-if=true会渲染内容,false不会渲染内容;v-show会直接渲染内容-->
    <!--显示form-->
    <el-row v-show="renderFormShow">
      <dynamic-form :config="someConfig" :value="someData"></dynamic-form>
    </el-row>
    <!--显示url-->
    <el-row v-if="!renderFormShow">
      <abs-bond-deal v-if="showPage == 'absBondDeal'"></abs-bond-deal>
      <bond-cfx v-if="showPage == 'bondCfx'"></bond-cfx>
      <bond-deal v-if="showPage == 'bondDeal'"></bond-deal>
      <bond-exercise v-if="showPage == 'bondExercise'"></bond-exercise>
      <buyout-deal v-if="showPage == 'buyoutDeal'"></buyout-deal>
      <clear-cash-transfer v-if="showPage == 'clearCashTransfer'"></clear-cash-transfer>
      <clear-rate v-if="showPage == 'clearRate'"></clear-rate>
      <clear-transfer-info-add-wf v-if="showPage == 'clearTransferInfoAdd_wf'"></clear-transfer-info-add-wf>
      <custom-deal v-if="showPage == 'customDeal'"></custom-deal>
      <custom-dividend v-if="showPage == 'customDividend'"></custom-dividend>
      <custom-rate v-if="showPage == 'customRate'"></custom-rate>
      <custom-rate-spv v-if="showPage == 'customRateSpv'"></custom-rate-spv>
      <custom-retirement v-if="showPage == 'customRetirement'"></custom-retirement>
      <custom-value-spv v-if="showPage == 'customValueSpv'"></custom-value-spv>
      <fund-cwjj-jyqr v-if="showPage == 'fundCwjjJyqr'"></fund-cwjj-jyqr>
      <fund-cwjj-shjy v-if="showPage == 'fundCwjjShjy'"></fund-cwjj-shjy>
      <fund-cwjj-tqsq v-if="showPage == 'fundCwjjTqsq'"></fund-cwjj-tqsq>
      <fund-dividend v-if="showPage == 'fundDividend'"></fund-dividend>
      <fund-hbjj-jyqr v-if="showPage == 'fundHbjjJyqr'"></fund-hbjj-jyqr>
      <fund-hbjj-shjy v-if="showPage == 'fundHbjjShjy'"></fund-hbjj-shjy>
      <fund-hbjj-tqsq v-if="showPage == 'fundHbjjTqsq'"></fund-hbjj-tqsq>
      <fund-vol v-if="showPage == 'fundVol'"></fund-vol>
      <impawn-deal v-if="showPage == 'impawnDeal'"></impawn-deal>
      <intserv-assest v-if="showPage == 'intservAssest'"></intserv-assest>
      <jys-bond-crk v-if="showPage == 'jysBondCrk'"></jys-bond-crk>
      <jys-bond-deal v-if="showPage == 'jysBondDeal'"></jys-bond-deal>
      <jys-bond-exercise v-if="showPage == 'jysBondExercise'"></jys-bond-exercise>
      <jys-bond-jyshg v-if="showPage == 'jysBondJyshg'"></jys-bond-jyshg>
      <prod-adjust-base-wf v-if="showPage == 'prodAdjustBase_wf'"></prod-adjust-base-wf>
      <prod-adjust-delay-wf v-if="showPage == 'prodAdjustDelay_wf'"></prod-adjust-delay-wf>
      <prod-adjust-fee-wf v-if="showPage == 'prodAdjustFee_wf'"></prod-adjust-fee-wf>
      <prod-adjust-interest-rate-wf v-if="showPage == 'prodAdjustInterestRate_wf'"></prod-adjust-interest-rate-wf>
      <prod-adjust-open-days-wf v-if="showPage == 'prodAdjustOpenDays_wf'"></prod-adjust-open-days-wf>
      <prod-adjust-pay-interest-wf v-if="showPage == 'prodAdjustPayInterest_wf'"></prod-adjust-pay-interest-wf>
      <prod-adjust-val-plan-wf v-if="showPage == 'prodAdjustValPlan_wf'"></prod-adjust-val-plan-wf>
      <prod-expire-wf v-if="showPage == 'prodExpire_wf'"></prod-expire-wf>
      <prod-info v-if="showPage == 'prodInfo'"></prod-info>
      <shibor-borrow v-if="showPage == 'shiborBorrow'"></shibor-borrow>
      <shibor-rate v-if="showPage == 'shiborRate'"></shibor-rate>
      <shibor-retirement v-if="showPage == 'shiborRetirement'"></shibor-retirement>
      <shibor-store v-if="showPage == 'shiborStore'"></shibor-store>
    </el-row>
  </div>
</template>

<script>
  /* ajax请求 */
  import * as kk from '../../../../utils/k-utils'
  /* 动态表单 */
  import DynamicForm from './dynamicForm.vue'

  export default {
    name: 'FormMain',
    components: {
      // form配置
      DynamicForm,
      // url配置
      // 懒加载组件一个页面只显示一个组件
      AbsBondDeal: resolve => require(['../deal/absBondDeal.vue'], resolve),
      BondCfx: resolve => require(['../deal/bondCfx.vue'], resolve),
      BondDeal: resolve => require(['../deal/bondDeal.vue'], resolve),
      BondExercise: resolve => require(['../deal/bondExercise.vue'], resolve),
      BuyoutDeal: resolve => require(['../deal/buyoutDeal.vue'], resolve),
      ClearCashTransfer: resolve => require(['../deal/clearCashTransfer.vue'], resolve),
      ClearRate: resolve => require(['../deal/clearRate.vue'], resolve),
      ClearTransferInfoAddWf: resolve => require(['../deal/clearTransferInfoAdd_wf.vue'], resolve),
      CustomDeal: resolve => require(['../deal/customDeal.vue'], resolve),
      CustomDividend: resolve => require(['../deal/customDividend.vue'], resolve),
      CustomRate: resolve => require(['../deal/customRate.vue'], resolve),
      CustomRateSpv: resolve => require(['../deal/customRateSpv.vue'], resolve),
      CustomRetirement: resolve => require(['../deal/customRetirement.vue'], resolve),
      CustomValueSpv: resolve => require(['../deal/customValueSpv.vue'], resolve),
      FundCwjjJyqr: resolve => require(['../deal/fundCwjjJyqr.vue'], resolve),
      FundCwjjShjy: resolve => require(['../deal/fundCwjjShjy.vue'], resolve),
      FundCwjjTqsq: resolve => require(['../deal/fundCwjjTqsq.vue'], resolve),
      FundDividend: resolve => require(['../deal/fundDividend.vue'], resolve),
      FundHbjjJyqr: resolve => require(['../deal/fundHbjjJyqr.vue'], resolve),
      FundHbjjShjy: resolve => require(['../deal/fundHbjjShjy.vue'], resolve),
      FundHbjjTqsq: resolve => require(['../deal/fundHbjjTqsq.vue'], resolve),
      FundVol: resolve => require(['../deal/fundVol.vue'], resolve),
      ImpawnDeal: resolve => require(['../deal/impawnDeal.vue'], resolve),
      IntservAssest: resolve => require(['../deal/intservAssest.vue'], resolve),
      JysBondCrk: resolve => require(['../deal/jysBondCrk.vue'], resolve),
      JysBondDeal: resolve => require(['../deal/jysBondDeal.vue'], resolve),
      JysBondExercise: resolve => require(['../deal/jysBondExercise.vue'], resolve),
      JysBondJyshg: resolve => require(['../deal/jysBondJyshg.vue'], resolve),
      ProdAdjustBaseWf: resolve => require(['../deal/prodAdjustBase_wf.vue'], resolve),
      ProdAdjustDelayWf: resolve => require(['../deal/prodAdjustDelay_wf.vue'], resolve),
      ProdAdjustFeeWf: resolve => require(['../deal/prodAdjustFee_wf.vue'], resolve),
      ProdAdjustInterestRateWf: resolve => require(['../deal/prodAdjustInterestRate_wf.vue'], resolve),
      ProdAdjustOpenDaysWf: resolve => require(['../deal/prodAdjustOpenDays_wf.vue'], resolve),
      ProdAdjustPayInterestWf: resolve => require(['../deal/prodAdjustPayInterest_wf.vue'], resolve),
      ProdAdjustValPlanWf: resolve => require(['../deal/prodAdjustValPlan_wf.vue'], resolve),
      ProdExpireWf: resolve => require(['../deal/prodExpire_wf.vue'], resolve),
      ProdInfo: resolve => require(['../deal/prodInfo.vue'], resolve),
      ShiborBorrow: resolve => require(['../deal/shiborBorrow.vue'], resolve),
      ShiborRate: resolve => require(['../deal/shiborRate.vue'], resolve),
      ShiborRetirement: resolve => require(['../deal/shiborRetirement.vue'], resolve),
      ShiborStore: resolve => require(['../deal/shiborStore.vue'], resolve)
    },
    props: {
      // 保存列表页面传过来的数据，子组件接受父组件数据
      param: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        renderFormShow: false, // 用表单展示
        showPage: '', // 展示那个页面，renderFormShow=false
        // 动态表单配置
        someConfig: {
          inline: true,
          labelPosition: 'right',
          labelWidth: '160px',
          size: 'mini',
          statusIcon: true,
          formItemList: [] // 表单字段定义
        },
        // 动态表单数据
        someData: {}
      }
    },
    // 执行一次，且第一次执行
    mounted() {
      this.init()
      this.first = true
    },
    // 组件被激活，第一次不执行
    activated() {
      // this.param父组件改变该属性值
      if (this.first) {
        this.first = false
        return
      }
      // 刷新数据
      this.search(this.param)
    },
    methods: {
      // 初始化
      init() {
        // 刷新数据
        this.search(this.param)
      },
      // 查询数据
      search(requestSupportParams) {
        var _this = this
        var url = ''
        if (requestSupportParams.method === 'start') {
          url = '/conf/getFormConf.json?processName=' + requestSupportParams.processName
          kk.k_load_url('workflow', url, {}).then(rep => {
            rep = JSON.parse(rep)
            if (rep.status === '200') {
              var formConf = rep.data
              // 如果没有配置
              if (!formConf || (!formConf[0]['formId'] && !formConf[0]['formUrl'])) {
                alert('至少需要配置一个表单')
              }
              var formUrl = ''
              var formId = ''
              // 如果是开始节点
              if (requestSupportParams.method === 'start') {
                formUrl = formConf[0]['formUrl']
                formId = formConf[0]['formId']
              }
              _this.renderMain(formId, formUrl, true)
            } else {
              _this.$message(rep.message)
            }
          })
        } else {
          url = '/conf/getFormConf.json?processId=' + requestSupportParams.processId
          kk.k_load_url('workflow', url, {}).then(rep => {
            rep = JSON.parse(rep)
            if (rep.status === '200') {
              // 第0个为默认。
              var formConf = rep.data
              var processFormConf = formConf[0]
              var formId = processFormConf.formId
              var formUrl = processFormConf.formUrl
              // 如果是已完后任务，则不做任何处理，获取默认来显示
              if (requestSupportParams.refPage !== 'hisCompleteTasks') {
                for (var i = 1; i < formConf.length; i++) {
                  var taskFormConf = formConf[i]
                  if (taskFormConf.taskName === requestSupportParams.taskName) {
                    formId = taskFormConf.formId || formId// 覆盖默认值
                    formUrl = taskFormConf.formUrl || formUrl
                    break
                  }
                }
              }
              _this.renderMain(formId, formUrl)
            } else {
              _this.$message(rep.message)
            }
          })
        }
      },
      // 获取表单信息并显示出来
      renderMain(formId, formUrl, isStart) {
        // iframe渲染优先
        if (formUrl) {
          this.renderFormShow = false // 用url展示
          this.renderIframe(formUrl, this.param)
        } else {
          this.renderFormShow = true // 用表单展示
          this.renderForm(formId, isStart)
        }
      },
      // 渲染url
      renderIframe(formUrl, requestSupportParams) {
        // 案例 'deal/bondDeal.html' 得到bondDeal
        var start = formUrl.lastIndexOf('/')
        var end = formUrl.lastIndexOf('.')
        var page = formUrl.substring(start + 1, end)
        // 使用路由切换页面
        this.showPage = page // 展示那个页面，renderFormShow=false
      },
      // ----------------------------------公共函数----------------------------------
      // 将obj1对象的数据拷贝到obj2对象
      copyObj(obj1, obj2) {
        for (var key in obj1) {
          // 原型对象不拷贝
          if (key === '__proto__') {
            continue
          }
          // 不存在的属性不添加
          if (!obj2.hasOwnProperty(key)) {
            continue
          }
          // 自动将number转换成string
          if (typeof obj1[key] === 'number') {
            obj1[key] = '' + obj1[key]
          }
          obj2[key] = obj1[key]
        }
      },
      // 数组通过属性查找 例如 arr = [obj,obj]
      findWhere(arr, obj) {
        for (var i = 0; i < arr.length; i++) {
          for (var key in obj) {
            // key相等,value也相等
            if (arr[i].hasOwnProperty(key) && arr[i][key] === obj[key]) {
              return arr[i]
            }
          }
        }
        return {}
      },
      // 数组通过属性查找 例如 arr = [obj,obj]
      findWhereAll(arr, obj) {
        var resultData = []
        for (var i = 0; i < arr.length; i++) {
          for (var key in obj) {
            // key相等,value也相等
            if (arr[i].hasOwnProperty(key) && arr[i][key] === obj[key]) {
              resultData.push(arr[i])
            }
          }
        }
        return resultData
      },
      // ----------------------------------表单处理----------------------------------
      // 渲染表单
      renderForm(formId, isStart) {
        // 显示表单信息
        this.renderFormShow = true
        var _this = this
        // 加载数据
        var url = '/form/design/get.json?id=' + formId
        kk.k_load_url('workflow', url, {}).then(rep => {
          rep = JSON.parse(rep)
          if (rep.status === '200') {
            // console.log(rep.data)
            var conf = JSON.parse(rep.data.json)
            // 渲染表单
            _this.renderFormHandler(conf)
            // 数据回填
            _this.fill_formn_data(_this.param)
          } else {
            _this.$message('获取表结构信息失败')
          }
        })
      },
      // 渲染表单
      renderFormHandler(fieldMat) {
        // console.log(fieldMat)
        // fieldMat = [[],[],...]
        var dynamicFormItem = []
        var item = {}
        var temp = {}
        for (var i = 0; i < fieldMat.length; i++) {
          for (var j = 0; j < fieldMat[i].length; j++) {
            item = fieldMat[i][j]
            // console.log(item)
            // 没有字段定义
            if (!item.hasOwnProperty('fieldConf') || item['fieldConf'] === null || item['fieldConf'] === '') {
              continue
            }
            // 一行一列 一行两列 一行三列 bootstrap与element-ui布局是不一样的
            item['fieldConf']['span'] = parseInt(item.col) * 2
            // 普通输入框处理
            if (item['fieldConf']['fieldType'] === 'k-field-text') {
              temp = this.k_field_text_handler(item['fieldConf'])
              dynamicFormItem.push(temp)
            } else if (item['fieldConf']['fieldType'] === 'k-field-select') {
              // 下拉输入框处理 如果不修改当成input处理
              temp = this.k_field_select_handler(item['fieldConf'])
              dynamicFormItem.push(temp)
            } else if (item['fieldConf']['fieldType'] === 'k-field-date') {
              // 时间框
              temp = this.k_field_date_handler(item['fieldConf'])
              dynamicFormItem.push(temp)
            } else {
              // 默认处理，普通输入框处理
              temp = this.k_field_text_handler(item['fieldConf'])
              dynamicFormItem.push(temp)
            }
          }
        }
        // 组建表单model
        var formModel = {}
        for (var k = 0; k < dynamicFormItem.length; k++) {
          formModel[dynamicFormItem[k].key] = dynamicFormItem[k].value
        }
        // 动态表单渲染
        this.someConfig.formItemList = dynamicFormItem
        this.someData = formModel
      },
      // 时间输入框处理
      k_field_date_handler(item) {
        var temp = {
          type: 'date',
          key: item.name,
          label: item.displayName,
          value: '',
          placeholder: '',
          span: item.span,
          disable: true, // 属性意思查看官网
          readonly: true
        }
        return temp
      },
      // 下拉框处理
      k_field_select_handler(item) {
        // 下拉输入框
        var temp = {
          type: 'select',
          key: item.name,
          label: item.displayName,
          value: '',
          placeholder: '',
          span: item.span,
          disable: true, // 属性意思查看官网
          readonly: true,
          filterable: false,
          clearable: false,
          options: []
        }
        return temp
      },
      // 普通输入框处理
      k_field_text_handler(item) {
        var temp = {
          type: 'input',
          subtype: 'text',
          key: item.name,
          label: item.displayName,
          value: '',
          placeholder: '',
          span: item.span,
          disable: true, // 属性意思查看官网
          readonly: true
        }
        return temp
      },
      // 数据回填
      fill_formn_data(requestSupportParams) {
        // 如果是任务详情页,那就获取approvalId对应的提交表单的原始数据来进行展示
        if (requestSupportParams.taskDetail === 'true') {
          this.fill_form_data_detail(requestSupportParams)
        } else {
          this.fill_form_data_main(requestSupportParams)
        }
      },
      // 数据回填-主要方式
      fill_form_data_main(requestSupportParams) {
        var _this = this
        var url = '/formData/listLatestFormData.json?processInstanceId=' + requestSupportParams.processInstanceId
        kk.k_load_url('workflow', url, {}).then(rep => {
          rep = JSON.parse(rep)
          // console.log(rep)
          if (rep.status === '200') {
            var formData = rep.data
            var params = {}
            // 转换为params
            for (var i = 0; i < formData.length; i++) {
              params[formData[i].fieldName] = formData[i].fieldValue
            }
            // console.log(params)
            _this.copyObj(params, _this.someData)
            // 下拉框显示值
            _this.fill_form_select(params)
          } else {
            _this.$message('获取表结构信息失败')
          }
        })
      },
      // 数据回填-详情页
      fill_form_data_detail(requestSupportParams) {
        var _this = this
        var url = '/formData/getSubmitParamsByApprovalId.json?approvalId=' + requestSupportParams.approvalId
        kk.k_load_url('workflow', url, {}).then(rep => {
          rep = JSON.parse(rep)
          if (rep.status === '200') {
            // console.log(rep.data)
            _this.copyObj(rep.data, _this.someData)
            // 下拉框显示值
            _this.fill_form_select(rep.data)
          } else {
            _this.$message('获取表结构信息失败')
          }
        })
      },
      // 数据回填-下拉框显示值
      fill_form_select(params) {
        // 获取字段定义
        var fieldDefine = this.someConfig.formItemList
        // 找到select下拉框
        var arr = this.findWhereAll(fieldDefine, { type: 'select' })
        var key = ''
        for (var i = 0; i < arr.length; i++) {
          key = arr[i].key
          this.someData[key] = params[key + '_displaylable']
        }
      }
    }
  }
</script>

<style scoped>
  /*让文本可以被选中*/
  .home {
    -moz-user-select: text; /*火狐*/
    -webkit-user-select: text; /*webkit浏览器*/
    -ms-user-select: text; /*IE10*/
    -khtml-user-select: text; /*早期浏览器*/
    user-select: text;
  }
  .wf_h {
    font-size: 18px;
    font-family: inherit;
    font-weight: 500;
    line-height: 1.1;
    color: inherit;
  }
</style>
